﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EONFULLSIN.Utils
{
    public class EFDAL
    {
        private static readonly Lazy<EFDAL> instance = new Lazy<EFDAL>(() => new EFDAL());
        public static EFDAL Instance => instance.Value;

        public bool AddModel<T>(T model) where T : class, new()
        {
            return DBHelper.DbContext.Insert(model).ExecuteAffrows() > 0;
        }

        public bool AddModels<T>(List<T> models) where T : class, new()
        {
            //var str = DbConfig.DbContext.Insert(models).ToSql();
            return DBHelper.DbContext.Insert(models).ExecuteAffrows() > 0;
        }

        public bool DeleteModel<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var sql = DBHelper.DbContext.Delete<T>().Where(exp).ToSql();
            LoggerHelper.Logger.Error(sql);
            return DBHelper.DbContext.Delete<T>().Where(exp).ExecuteAffrows() > 0;
        }

        public T GetModel<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            return DBHelper.DbContext.Select<T>().Where(exp).ToOne();
        }

        public List<T> GetModelList<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var str = DBHelper.DbContext.Select<T>().Where(exp).ToSql();
            LoggerHelper.Logger.Error(str);
            return DBHelper.DbContext.Select<T>().Where(exp).ToList();
        }

        public bool UpdateModel<T>(Expression<Func<T, bool>> exp, Expression<Func<T, T>> exp2) where T : class, new()
        {
            var str = DBHelper.DbContext.Update<T>().Set(exp2).Where(exp).ToSql();
            LoggerHelper.Logger.Error(str);
            return DBHelper.DbContext.Update<T>().Set(exp2).Where(exp).ExecuteAffrows() > 0;
        }

        public bool CheckExist<T>(Expression<Func<T, bool>> exp) where T : class, new()
        {
            var str = DBHelper.DbContext.Select<T>().Where(exp).ToSql();
            LoggerHelper.Logger.Error(str);
            return DBHelper.DbContext.Select<T>().Any(exp);
        }

        public bool UpdateModelSuper<T>(Expression<Func<T, bool>> exp, T t) where T : class, new()
        {
            var str = DBHelper.DbContext.Update<T>().SetSource(t).Where(exp).ToSql();
            LoggerHelper.Logger.Error(str);
            return DBHelper.DbContext.Update<T>().SetSource(t).Where(exp).ExecuteAffrows() > 0;
        }
    }
}